package com.webapi.core.dao.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import com.webapi.core.model.persist.Order;


@SuppressWarnings("unchecked")
public abstract class EntityDao<T, PK extends Serializable> extends
    MyHibernateDaoSupport implements BaseDao<T, PK> {

	protected Class<T> clazz;
	
	public EntityDao() {
		clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public T get(PK id) {
		return super.getHibernateTemplate().get(clazz, id);
	}

	@Override
    public List<T> get(String cd) {
	    String hql = "FROM " + clazz.getSimpleName() + " t WHERE ";
	    if (clazz.getName().equals(Order.class.getName())) {
	        hql += " t.cd = ?";
	    } else {
	        hql += " t.order.cd = ?";
	    }
        return super.getHibernateTemplate().find(hql, cd);
    }

	@Override
	public List<T> get(List<String> cds) {
		String hql = "FROM " + clazz.getSimpleName() + " t WHERE ";
	    if (clazz.getName().equals(Order.class.getName())) {
	        hql += " t.cd";
	    } else {
	        hql += " t.order.cd";
	    }
	    hql += " IN (" + buildInSentence(cds.size()) + ")";
        return super.getHibernateTemplate().find(hql, cds.toArray());
	}
	
	private String buildInSentence(int len) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i ++) {
			sb.append("?,");
		}
		return sb.deleteCharAt(sb.length() - 1).toString();
	}

	@Override
	public List<T> all() {
    	return super.getHibernateTemplate().find("FROM " + clazz.getSimpleName());
	}

	public void save(T e) {
		super.getHibernateTemplate().save(e);
	}
	
	public void update(T e) {
		super.getHibernateTemplate().update(e);
	}

}
